
import Taro, { useDidShow } from '@tarojs/taro';
import { MaterialIcons } from 'taro-icons';
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { View, Text, ScrollView } from '@tarojs/components';
import ImageLoader from '../../components/ImageLoader';

import { SessionItems } from '../../types/chat';
import { userLoginLimit } from '../../contexts/store';
import { DataLoadingView } from '../../components/dataLoading';
import { getChatSessionListApi, setChatSessionStatusApi, deleteChatSessionApi } from '../../api/chat';


import './index.scss';

/**
 * 会话列表页面组件
 * 展示与教练的聊天会话列表
 */
const SessionListComponent: React.FC = () => {
  const pageSize: number = 20; // 每页显示的会话数量
  const [hasMore, setHasMore] = useState(true);
  const [isLoading, setIsLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [sessionList, setSessionList] = useState<SessionItems[]>([]);

  // 获取初始会话列表数据
  const fetchInitialData = useCallback(async () => {
    // 检查登录状态
    const isLogin = userLoginLimit('获取个人聊天，需登录服务');
    if (!isLogin) {
      setIsLoading(false); // 用户未登录，手动设置加载状态为false
      return;
    }
    
    setCurrentPage(1); // 每次进入页面重置为第一页
    setIsLoading(true);
    try {
      const res: any = await getChatSessionListApi(1, pageSize);
      if (res.code === 200) {
        setSessionList(res.data || []);
        setHasMore(res.has_more || false);
      }
    } catch (error) {
      console.error('Failed to fetch initial sessions:', error);
    } finally {
      setIsLoading(false);
    }
  }, [pageSize]);


  // 页面每次显示时重新获取数据
  useDidShow(() => {
    fetchInitialData();
  });

  // 打开与教练的聊天界面
  const openChatRoom = async (item: SessionItems) => {
    await setChatSessionStatusApi(item.id);
    Taro.navigateTo({
      url: `/pages/chat/index?sessionId=${item.id}&coachId=${item.coach_id}&coachName=${encodeURIComponent(item.coach.username)}&coachAvatar=${encodeURIComponent(item.coach.avatar)}&source=0`
    });
  };

  // 删除会话
  const handleDeleteSession = async (sessionId: number) => {
    try {
      const res = await deleteChatSessionApi(sessionId);
      if (res.code === 200) {
        setSessionList(prev => prev.filter(item => item.id !== sessionId));
        Taro.showToast({
          title: '会话已删除',
          icon: 'success'
        });
      } else {
        Taro.showToast({
          title: '删除失败，请重试',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('删除会话失败:', error);
      Taro.showToast({
        title: '删除失败，请重试',
        icon: 'none'
      });
    }
  };

  // 加载更多数据
  const loadMoreData = async () => {
    if (isLoading || !hasMore) return;
    setIsLoading(true);
    try {
      const nextPage = currentPage + 1;
      const res: any = await getChatSessionListApi(nextPage, pageSize);
      if (res.code === 200) {
        setSessionList(prev => [...prev, ...(res.data || [])]);
        setCurrentPage(nextPage);
        setHasMore(res.has_more || false);
      } else {
        setHasMore(false);
      }
    } catch (error) {
      console.error('Failed to load more sessions:', error);
      setHasMore(false);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <View className="page-container session-list-container">
      {/* 页面头部 */}
      <View className="session-header">
        <Text className="session-header-title">会话列表</Text>
      </View>

      {/* 会话列表 */}
      <ScrollView 
        className="session-scrollview"
        scrollY
        onScrollToLower={loadMoreData}
        showsVerticalScrollIndicator={false}
      >
        {sessionList.map(item => (
          <View 
            key={item.id} 
            className="session-item"
            onClick={() => openChatRoom(item)}
          >
            {/* 头像和未读消息数 */}
            <View className="session-avatar-container">
              <ImageLoader 
                className="session-avatar"
                src={item.coach.avatar}
                mode="aspectFill"
              />
              {item.unread > 0 && (
                <View className="session-unread-badge">
                  <Text className="session-unread-text">{item.unread}</Text>
                </View>
              )}
            </View>

            {/* 会话信息 */}
            <View className="session-info">
              <View className="session-top">
                <Text className="session-coach-name">{item.coach.username}</Text>
                <Text className="session-timestamp">{item.timestamp}</Text>
              </View>
              <Text className="session-last-message" numberOfLines={1}>
                {item.last_message?item.last_message.length > 16? item.last_message.substring(0, 16)+'...':item.last_message: ''}
              </Text>
            </View>

            {/* 删除按钮 */}
            <View 
              className="session-delete-button"
              onClick={(e) => {
                e.stopPropagation();
                handleDeleteSession(item.id);
              }}
            >
              <Text className="session-delete-icon">
                <MaterialIcons name="close" color="#ff4757" size={16} />
              </Text>
            </View>
          </View>
        ))}

        {/* 加载更多 */}
        {isLoading && (
          <DataLoadingView />
        )}

        {/* 没有更多数据 */}
        {!hasMore && sessionList.length > 0 && (
          <View className="session-no-more-container">
            <Text className="session-no-more-text">没有更多数据了</Text>
          </View>
        )}

        {/* 空状态 */}
        {!isLoading && sessionList.length === 0 && (
          <View className="session-empty-container">
            <Text className="session-empty-text">暂无会话</Text>
          </View>
        )}
      </ScrollView>
    </View>
  );
};

// 使用AppProvider包裹组件
export default SessionListComponent;